#include <iostream>
#include <fstream>
#include "contacts.pb.h" //默认先从当前目录；然后没有再去系统对应目录
#include <string>

using namespace std;

void printcontacts(contacts::Contacts cs)
{

    for (int i = 0; i < cs.contacts_size(); i++)
    {

        cout << "\n---------------联系人" << i + 1 << "---------------" << endl;
        // 取出对应联系人“：

        contacts::PersonInfo personinfo = cs.contacts(i);

        cout << "联系人姓名：" << personinfo.name() << endl;
        cout << "联系人年龄：" << personinfo.age() << endl;

        for (int j = 0; j < personinfo.phone_size(); j++)
        {
            contacts::PersonInfo_Phone phone = personinfo.phone(j);
            cout << "联系人电话" << j + 1 << ":" << phone.number() << endl;
            cout << "   (" << phone.PhoneType_Name(phone.type()) << ")" << endl;
        }

        if (cs.contacts(i).data().Is<contacts::Address>())
        {
            contacts::Address address;
            cs.contacts(i).data().UnpackTo(&address);
            // 进行判断是否存在；因为之前存入的数据没有设置因此read的时候就不打印
            if (!address.home_address().empty())
            {
                cout << "联系人家庭地址：" << address.home_address() << endl;
            }
            if (!address.home_address().empty())
            {
                cout << "联系人工作地址：" << address.work_address() << endl;
            }
        }

        switch (cs.contacts(i).contact_case())
        {

        case contacts::PersonInfo::ContactCase::kQq:
            cout << "联系人qq: " << cs.contacts(i).qq() << endl;
            break;

        case contacts::PersonInfo::ContactCase::kWechat:
            cout << "联系人微信号: " << cs.contacts(i).wechat() << endl;
            break;
        default:
            break;
        }

         if (cs.contacts(i).comment_size()) {
            cout << "备注信息：" << endl;
        }
        for (auto it = cs.contacts(i).comment().cbegin(); it !=cs.contacts(i).comment().cend(); it++) {
            cout << "   " << it->first << ": " << it->second << endl;
        }
    }
}

int main()
{

    contacts::Contacts contacts;

    // 完成读取出来到protobuf对象；然后在打印：
    fstream input("contacts.bin", ios::in | ios::binary);
    if (!contacts.ParseFromIstream(&input))
    {
        cerr << "parse error!" << endl;
        input.close();
        return -1;
    }

    printcontacts(contacts);
    return 0;
}